package com.liangzhong.proxy.friend
{
	import com.adobe.serialization.json.JSON;
	import com.common.stdlib.StringUtil;
	import com.common.utils.Debug;
	import com.liangzhong.commandconst.commandType.MainCommandType;
	import com.liangzhong.commandconst.friend.CMD_Friend;
	import com.liangzhong.commandconst.logic.CMD_Logic;
	import com.liangzhong.constants.HttpRequestConst;
	import com.liangzhong.constants.NotificationConstants;
	import com.liangzhong.errortip.ErrorTips;
	import com.liangzhong.events.AppEventDispatcher;
	import com.liangzhong.events.NotifierEvent;
	import com.liangzhong.global.CMD_Head;
	import com.liangzhong.model.AppData;
	import com.liangzhong.model.friend.FriendManager;
	import com.liangzhong.model.friend.FriendServerDataParse;
	import com.liangzhong.model.friend.vo.FriendHonorVo;
	import com.liangzhong.model.friend.vo.FriendInfoVo;
	import com.liangzhong.model.friend.vo.FriendInviteVo;
	import com.liangzhong.model.friend.vo.FriendMatchResultVo;
	import com.liangzhong.model.friend.vo.FriendVo;
	import com.liangzhong.proxy.BaseProxy;
	import com.liangzhong.proxy.ProxyUtils;
	import com.liangzhong.proxyconstant.chat.ChatProxyConstant;
	import com.liangzhong.proxyconstant.friend.FriendProxyConstant;
	import com.socket.clientsocket.IClientSocket;
	import com.socket.clientsocket.IClientSocketHandler;
	
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	
	import lz.controls.Alert;
	
	/**
	 * FriendProxy
	 * @author lake
	 * 
	 */	
	public class FriendProxy extends BaseProxy implements IClientSocketHandler
	{
		public static const ProxyName :String = "FriendProxy";
		/**
		 * 获取好友列表 result
		 */		
		public static const FRIEND_GETFRIENDLIST_RESULT	:String = "Server/Friend/FRIEND_GETFRIENDLIST_RESULT";
		/**
		 * 获取好友俱乐部信息 result
		 */		
		public static const FRIEND_GETFRIENDCLUBINFO_RESULT :String = "Server/Friend/FRIEND_GETFRIENDCLUBINFO_RESULT";
		/**
		 * 获取好友战绩信息 result
		 */		
		public static const FRIEND_GETFRIENDSCOREINFO_RESULT :String = "Server/Friend/FRIEND_GETFRIENDSCOREINFO_RESULT";
		/**
		 * 获取好友荣誉信息 result
		 */		
		public static const FRIEND_GETFRIENDHONORINFO_RESULT :String = "Server/Friend/FRIEND_GETFRIENDHONORINFO_RESULT";
		/**
		 *获取在线列表 result 
		 */		
		public static const FRIEND_GETONLINELIST_RESULT	:String = "Server/Friend/FRIEND_GETONLINELIST_RESULT";
		/**
		 *接受到玩家邀请 
		 */		
		public static const RECEIVE_INVITE_RESULT			:String = "Server/Friend/RECEIVE_INVITE_RESULT";
		/**
		 *收到好友挑战请求 
		 */		
		public static const RECEIVE_CHALLENGE_RESULT		:String = "Server/Friend/RECEIVE_CHALLENGE_RESULT";
		/**
		 *收到好友取消挑战请求 
		 */		
		public static const RECEIVE_CHALLENGE_CANCEL_RESULT:String = "Server/Friend/RECEIVE_CHALLENGE_CANCEL_RESULT";
		/**
		 *比赛开始返回信息 
		 */		
		public static const MATCH_START_DATA_RESULT		:String = "Server/Friend/MATCH_START_DATA_RESULT";
		/**
		 *比赛结果 
		 */		
		public static const MATCH_RESULT_RESULT			:String = "Server/Friend/MATCH_RESULT_RESULT";
		/**
		 *好友挑战请求返回 
		 */		
		public static const CHALLENGE_FRIEND_RESULT		:String = "Server/Friend/CHALLENGE_FRIEND_RESULT";
		/**
		 *删除好友返回 
		 */		
		public static const DELETE_FRIEND_RESULT			:String = "Server/Friend/DELETE_FRIEND_RESULT";
		
		
		/**
		 * 
		 */
		private var _friendDataManager:FriendManager;
		public function FriendProxy(proxyName:String = ProxyName, data:Object=null)
		{
			super(proxyName, data);
			_friendDataManager = AppData.getInstance().friendManager;
		}
		/**
		 *获取好友列表 
		 * 
		 */		
		public function getFriendList():void
		{
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.FRIEND_GETFRIENDLIST;
			ProxyUtils.instance.webClient(getFriendListRes,variables,false);
		}
		/**
		 *获取好友列表  result
		 */	
		private function getFriendListRes(data :Object):void
		{
			var str:String = String(data);
			var resultObj :Object;
			try
			{
				resultObj = JSON.decode(str)[0];
			}
			catch(e :Error)
			{
//				trace("getFriendList:",e);
//				trace("data:",str);
				return;
			}
			if(resultObj.retcode != 0)
			{
				return;
			}
			_friendDataManager.checkTime = AppData.getInstance().time;
			var tList :Array = resultObj.club_friend_info;
			_friendDataManager.parseFriendList(tList);
			//			AppData.getInstance().friendManager.invitedfriend = resultObj.invitedfriend;
			_friendDataManager.invitedfriend = 0;
			_friendDataManager.changeinviteNumber( resultObj.invitedfriend);
			this.sendNotification(FriendProxyConstant.UPDATA_FRIEND_LIST,{type:1});
		}
		/**
		 *请求在线的好友 
		 * 
		 */
		public function requestOnlineFriend():void
		{
			
		}
		/**
		 *获得在线好友  
		 * 
		 */
		public function getOnlineFriend($data:Object):void
		{
			
		}
		/**
		 *获取好友俱乐部信息 
		 * {vo:f,type:1}
		 *  type 1-->查看信息 2-->挑战
		 * @param cid
		 */		
		private var lookFriendVo :FriendInfoVo;
		public function getFriendClubInfo($obj:Object):void
		{
			lookFriendVo = $obj.vo;
			if($obj.type == 2)//请求挑战
			{
				//				var sendBuf :ByteArray = 
				//					CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 4,MainCommandType.INTERACTIVE,CMD_Friend.CHALLENGE_FRIEND);
				//				sendBuf.writeInt(lookFriendVo.friendid);
				//				sendBuf.position = 0;
				//				clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
				lookFriendVo.isStartTime = true;
				requestFriendinfo();
				return;
			}
			
			requestFriendinfo();
		}
		/**
		 *请求好友信息 
		 * 
		 */
		private function requestFriendinfo():void
		{
			requestFriendCount();
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.FRIEND_GETFRIENDCLUBINFO;
			variables.cid = lookFriendVo.friendid;
			ProxyUtils.instance.webClient(getFriendClubInfoRes,variables,false);
		}
		/**
		 *获取好友俱乐部信息 res 
		 * @param data
		 * 
		 */		
		private function getFriendClubInfoRes(data :Object):void
		{
			var obj:Object = ProxyUtils.instance.analysisHttpData(data,FriendProxy);
			if(obj.retcode == 0)
			{
				if(obj.clubid != lookFriendVo.friendid)return;
				lookFriendVo.getData(obj);
				lookFriendVo.isUpdata = true;
				this.sendNotification(NotificationConstants.LOOK_UP_INFO,{vo:lookFriendVo});
			}
			else
			{
				
			}
		}
		/**
		 * 请求挑战返回
		 * 判断是否直接进入比赛-->不是 取好友的数据并有时间跳转
		 * 是 直接进入比赛
		 * 
		 */
		private function getFriendFight(buffer:ByteArray):void
		{
			//是否直接进入比赛 是return;
			
			//是否需要请求数据
			lookFriendVo.isStartTime = true;
			if(lookFriendVo.isRequestInfo)
			{
				requestFriendinfo();
			}else
			{
				lookFriendVo.isUpdata = false;
				this.sendNotification(NotificationConstants.LOOK_UP_INFO,{vo:lookFriendVo});
			}
			
		}
		
		
		/**
		 * 数据读取
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @param clientSocket
		 * @return 
		 */		
		override public function onSocketRead(mainCmdID:uint,
											  subCmdID:uint,
											  buffer:ByteArray, 
											  dataSize:int, 
											  clientSocket:IClientSocket):Boolean
		{
			switch(mainCmdID)
			{
				case MainCommandType.INTERACTIVE:
				{
					return onDeal(mainCmdID,subCmdID,buffer,dataSize);
				}
				case MainCommandType.MATCH:
				{
					return onDealMatch(mainCmdID,subCmdID,buffer,dataSize)
				}
					
			}
			return false;
		}
		/**
		 * 处理登陆信息
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @return 
		 * 
		 */		
		private function onDeal(mainCmdID:uint,
								subCmdID:uint,
								buffer:ByteArray, 
								dataSize:int):Boolean
		{
			var onLineList :Array;
			var uid			:int;
			var ret			:int;
			var strLen		:int;
			var name		:String;
			var retObj		:*;
			switch(subCmdID)
			{
				case CMD_Friend.NAME_INVITE:
					getNameInvite(buffer);
					return true;
				case CMD_Friend.AGREE_INVITE:
					getAgreeInvite(buffer);
					return true;
				case CMD_Friend.REFUSE_INVITE:
					getrefuseInvite(buffer);
					return true;
				case CMD_Friend.Invite_By_ID:
					getInvite_By_ID(buffer);
					return true;
				case CMD_Friend.RECEIVE_FRIEND_INVITE:
					gerreceive_friend_invite(buffer);
					return true;
				case CMD_Friend.DELETE_FRIEND:
					getDeleteFriend(buffer);
					return true;
				case CMD_Friend.RECOMMEND_FRIEND:
					getRecommendlist(buffer);
					return true;
//				case CMD_Friend.CHALLENGE_FRIEND://返回请求挑战
//					
//					return true;
				case CMD_Friend.RECEIVE_CHALLENGE://收到好友挑战请求
					
					return true;
				case CMD_Friend.CANCEL_CHALLENGE://取消挑战
					
					return true;
					
			}
			return false;
		}
		
		private function onDealMatch(mainCmdID:uint,
									 subCmdID:uint,
									 buffer:ByteArray, 
									 dataSize:int):Boolean
		{
			switch(subCmdID)
			{
				case CMD_Friend.CHALLENGE_FRIEND:
					getFrinedChanglle(buffer);
					return true;
			}
			return false;
		}
		
		/**
		 *名称邀请 
		 * 
		 */
		public function requestNameInvite($obj:Object):void
		{
			var len:int = StringUtil.getStringByteLength($obj.playerName);
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + len + 2,MainCommandType.INTERACTIVE,CMD_Friend.NAME_INVITE);
			sendBuf.writeUTF($obj.playerName);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *返回名称邀请 
		 * @param buffer
		 * 
		 */
		private function getNameInvite(buffer:ByteArray):void
		{
			var nReturn:int = buffer.readInt();
			if(nReturn ==0)
			{
				this.sendNotification(FriendProxyConstant.GET_NAME_INVITE,{status:true});
				Alert.showErrorTip("邀请成功");
			}
			else
			{
				Alert.showErrorTip(ErrorTips.instance.getCErrorTip(nReturn));
				this.sendNotification(FriendProxyConstant.GET_NAME_INVITE,{status:false});
				
			}
		}
		/**
		 * 同意邀请
		 * 
		 */
		public function requestAgreeInvite($obj:Object):void
		{
			var arr:Array = $obj.arr;
			var len:int = arr.length;
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + len * 4 + 2,MainCommandType.INTERACTIVE,CMD_Friend.AGREE_INVITE);
			sendBuf.writeShort(len);
			//			trace("请求长度：-->" + len);
			for(var i:int = 0;i < len;i++)
			{
				sendBuf.writeInt(arr[i]);
				//				trace("同意邀请ID-->"+ arr[i]);
			}
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 * 返回同意邀请 
		 * 更新好友列表
		 */
		private function getAgreeInvite(buffer:ByteArray):void
		{
			var nReturn:int = buffer.readInt();
			if(nReturn ==0)
			{
				var len:int = buffer.readShort();
				var friendVo:FriendVo;
				//				trace("同意长度——————————————————————————" + len);
				for(var i:int = 0;i < len;i++)
				{
					friendVo = new FriendVo();
					friendVo.analysisByte(buffer);
					_friendDataManager.addFriend(friendVo);
					_friendDataManager.deleteInviteVoById(friendVo.friendid);
					//					trace("返回同意ID——————————————————————————"+ friendVo.friendid);
				}
				_friendDataManager.changeinviteNumber(-len);
				_friendDataManager.sortFriendList();
				this.sendNotification(FriendProxyConstant.UPDATA_FRIEND_LIST,{status:true,type:1});
				Alert.showErrorTip("成功加入好友列表中");
			}
			else
			{
				Alert.showErrorTip(ErrorTips.instance.getCErrorTip(nReturn));
				this.sendNotification(FriendProxyConstant.UPDATA_FRIEND_LIST,{status:false});
				
			}
		}
		/**
		 *拒绝邀请 
		 * 
		 * @param $obj
		 * 
		 */
		public function requestrefuseInvite($obj:Object):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 4,MainCommandType.INTERACTIVE,CMD_Friend.REFUSE_INVITE);
			sendBuf.writeInt($obj.id);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 * 返回拒绝邀请
		 * 更换邀请列表
		 */
		private function getrefuseInvite(buffer:ByteArray):void
		{
			var nReturn:int = buffer.readInt();
			if(nReturn ==0)
			{
				var id:int = buffer.readInt();
				_friendDataManager.deleteInviteVoById(id);
				_friendDataManager.changeinviteNumber(-1);
				//				if(_friendDataManager.invitedfriend < 0)_friendDataManager.invitedfriend = 0;
				
				this.sendNotification(FriendProxyConstant.UPDATA_FRIEND_LIST,{status:true,type:2});
				Alert.showErrorTip("操作成功");
			}
			else
			{
				Alert.showErrorTip(ErrorTips.instance.getCErrorTip(nReturn));
				this.sendNotification(FriendProxyConstant.UPDATA_FRIEND_LIST,{status:false});
				
			}
		}
		/**
		 *邀请好友 id 
		 * @param $obj
		 * 
		 */
		public function requestInvite_By_ID($obj:Object):void
		{
			var arr:Array = $obj.array;
			var len:int = arr.length;
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 4 * len + 2,MainCommandType.INTERACTIVE,CMD_Friend.Invite_By_ID);
			sendBuf.writeShort(len);
			for(var i:int = 0;i < len;i++)
			{
				sendBuf.writeInt(arr[i]);
			}
			
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 * 返回邀请好友 
		 * @param buffer
		 * 
		 */
		private function getInvite_By_ID(buffer:ByteArray):void
		{
			var nReturn:int = buffer.readInt();
			if(nReturn ==0)
			{
				//				var id:int = buffer.readInt();
				//				
				//				
				//				this.sendNotification(FriendProxyConstant.UPDATE_RECOMMEND_FRIEND_LIST,{status:true,type:id});
				Alert.showErrorTip("操作成功");
			}
			else
			{
				Alert.showErrorTip(ErrorTips.instance.getCErrorTip(nReturn));
				this.sendNotification(FriendProxyConstant.UPDATE_RECOMMEND_FRIEND_LIST,{status:false});
				
			}
		}
		/**
		 *请求推荐好友列表 
		 * 
		 */
		public function requestRecommendList($obj:Object):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size ,MainCommandType.INTERACTIVE,CMD_Friend.RECOMMEND_FRIEND);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *返回推荐好友列表 
		 * @param buffer
		 * 
		 */
		private function getRecommendlist(buffer:ByteArray):void
		{
			var nReturn:int = buffer.readInt();
			if(nReturn ==0)
			{
				_friendDataManager.updataRecommendList(buffer);
				this.sendNotification(FriendProxyConstant.UPDATE_RECOMMEND_FRIEND_LIST,{status:true});
			}
			else
			{
				Alert.showErrorTip(ErrorTips.instance.getCErrorTip(nReturn));
				this.sendNotification(FriendProxyConstant.UPDATE_RECOMMEND_FRIEND_LIST,{status:false});
				
			}
		}
		/**
		 *请求受到邀请的好友  
		 * 
		 */
		public function requestReceiveInviteList():void
		{
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.FRIEND_RECEIVE_INVITE;
			ProxyUtils.instance.webClient(getReceiveInviteList,variables);
		}
		/**
		 *返回受到邀请好友的列表 
		 * 
		 */
		private function getReceiveInviteList($data:Object):void
		{
			var obj:Object = ProxyUtils.instance.analysisHttpData($data,FriendProxy);
			if(obj.retcode == 0)
			{
				_friendDataManager.analysisInvoite(obj);
				this.sendNotification(FriendProxyConstant.GET_RECEIVE_INVITE,{status:true});
			}else
			{
				//				Debug.echo("++++++++"+ErrorTips.instance.getErrorTip(obj.msg));
				this.sendNotification(FriendProxyConstant.GET_RECEIVE_INVITE,{status:false});
			}
		}
		/**
		 *接收到好友的邀请 
		 * @param buffer
		 * 
		 */
		private function gerreceive_friend_invite(buffer:ByteArray):void
		{
			var len:int = buffer.readShort();
			var friendVo:FriendVo
			for(var i:int = 0;i < len;i++)
			{
				friendVo= new FriendVo();
				friendVo.analysisinvite(buffer);
				_friendDataManager.addInviteVo(friendVo);
			}
			
			_friendDataManager.changeinviteNumber(len);
		}
		
		/**
		 *删除好友  
		 * @param $obj
		 * 
		 */
		public function requestDeleteFriend($obj:Object):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 4 ,MainCommandType.INTERACTIVE,CMD_Friend.DELETE_FRIEND);
			sendBuf.writeInt($obj.id);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
			
			
			
		}
		/**
		 *返回删除 好友  
		 * @param buffer
		 * 
		 */
		private function getDeleteFriend(buffer:ByteArray):void
		{
			var nReturn:int = buffer.readInt();
			if(nReturn ==0)
			{
				//				this.sendNotification(FriendProxyConstant.UPDATE_RECOMMEND_FRIEND_LIST,{status:true});
				_friendDataManager.deleteFriendById(buffer.readInt());
				this.sendNotification(FriendProxyConstant.UPDATA_FRIEND_LIST,{status:true,type:1});
				Alert.showErrorTip("成功从好友列表中移除");
			}
			else
			{
				Alert.showErrorTip(ErrorTips.instance.getCErrorTip(nReturn));
				this.sendNotification(FriendProxyConstant.UPDATA_FRIEND_LIST,{status:false});
				//				this.sendNotification(FriendProxyConstant.UPDATE_RECOMMEND_FRIEND_LIST,{status:false});
				
			}
		}
		/**
		 *取消挑战 
		 * @param $obj
		 * 
		 */
		public function requesetCanelFight($obj:Object):void
		{
			//			var id:int = $obj.vo.friendid;
			//			var sendBuf :ByteArray = 
			//				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size ,MainCommandType.INTERACTIVE,CMD_Friend.CANCEL_CHALLENGE);//测试时，看下这个值是否正确
			//			sendBuf.writeInt(id);
			//			sendBuf.position = 0;
			//			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		
		/**
		 *请求好友挑战 
		 * 
		 */
		public function requestFriendChanglle($obj:Object):void
		{
			
			var vo :FriendInfoVo = $obj.vo;
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 4 ,MainCommandType.MATCH,CMD_Friend.CHALLENGE_FRIEND);
			sendBuf.writeInt(vo.friendid);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *请求挑战返回 
		 * @param buffer
		 * 
		 */
		private function getFrinedChanglle(buffer:ByteArray):void
		{
			var nturn:int = buffer.readInt();
			if(nturn == 0)
			{
//				trace("请求挑战返回" + nturn);
				AppData.getInstance().clubDatamanager.clubInfo.friendCount--;
			}else
			{
				Alert.showErrorTip(ErrorTips.instance.getCErrorTip(nturn));
			}
		}
		
		/**
		 *请求比赛结果 
		 * 
		 */
		public function requestMatchResult():void
		{
			
		}
		
		/**
		 *获得比赛结果 
		 * 
		 */
		private function getMatchResult($data:Object):void
		{
			var obj:Object = ProxyUtils.instance.analysisHttpData($data,FriendProxy);
			if(obj.retcode == 0)
			{
//				_friendDataManager.analysisInvoite(obj);
//				this.sendNotification(FriendProxyConstant.GET_RECEIVE_INVITE,{status:true});
			}else
			{
				//				Debug.echo("++++++++"+ErrorTips.instance.getErrorTip(obj.msg));
//				this.sendNotification(FriendProxyConstant.GET_RECEIVE_INVITE,{status:false});
				Alert.showErrorTip(ErrorTips.instance.getErrorTip(obj.retcode));
			}
		}
		
		
		/**
		 *请求好友的挑战次数 
		 * 
		 */
		private function requestFriendCount():void
		{
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.FRIEND_COUNT;
			ProxyUtils.instance.webClient(getFriendCount,variables,false);
		}
		private function getFriendCount($data:Object):void
		{
			var obj:Object = ProxyUtils.instance.analysisHttpData($data,FriendProxy);
			if(obj.retcode == 0)
			{
				var count:int = obj.friendcount;
				AppData.getInstance().clubDatamanager.clubInfo.friendCount = count;
				this.sendNotification(NotificationConstants.FRIEND_CHANGLLE_TIME);
			}else
			{
			}
		}
	}
}